#include "str_cli.h"
#include "sum.h"
#include <define.h>
#include <error.h>
#include <wrapfunc.h>
#include <sockfunc.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>


void 
str_cli(FILE *fp, int fd) {
	char readbuf[MAX_LINE], writebuf[MAX_LINE];
	while (fgets(writebuf, MAX_LINE, fp)) {
		Writen(fd, writebuf, strlen(writebuf));
		if (readline(fd, readbuf, MAX_LINE) <= 0) {
			error_msg("fail to readline");
			break;
		}
		error_msg(":%s", readbuf);
	}
}

void
str_cli_epipe(FILE *fp, int fd) {
	const char *msg = "test msg$";
	char readbuf[MAX_LINE], writebuf[MAX_LINE];
	while (fgets(writebuf, MAX_LINE, fp)) {
		// 关闭服务器 socket 客户端从 fgets 返回后，
		// 第一次写触发 socket RST
		// 第二次写触发 SIGPIPE 信号，而 write 返回 EPIPE 错误
		Writen(fd, msg, strlen(msg));
		sleep(1);
		Writen(fd, writebuf, strlen(writebuf));

		if (readline(fd, readbuf, MAX_LINE) <= 0) {
			error_msg("fail to readline");
			break;
		}
		error_msg(":%s", readbuf);
	}
}

void
str_cli09(FILE *fp, int fd) {
	char line[MAX_LINE];
	struct SumArgs args;
	struct SumResult result;
	while (fgets(line, MAX_LINE, fp)) {
		if (sscanf(line, "%d%d", &args.arg1, &args.arg2) != 2) {
			error_msg("invalid input");
			continue;
		}

		Writen(fd, &args, sizeof(args));
		Readn(fd, &result, sizeof(result));
		error_msg(":%ld", result.sum);
	}
}
